<?php
require_once dirname(realpath(__FILE__))."./../config/config.inc.php";

#---------------------------------------------------------------
function validatorValidateInput($input, $validityMode) {
  switch($validityMode) {
    # check if input is price --------------------
    case 'PRICE':
      if (preg_match('/^[0-9]*$/' ,$input)) return true;
      else return false;
      break;
    
    # check if input id is category --------------------
    case 'CATEGORY-ID':
      require CACHE_PATH.'category.cache.php';
      $isCategoryValid = false;
      foreach($categoriesCached as $categoryCached) {
        if (isset($categoryCached['childs'])) {
          foreach($categoryCached['childs'] as $child) {
            if ($child['id'] == $input) $isCategoryValid = true;
          }
        }
      }

      return $isCategoryValid;
      break;
      
    # check if input string is town --------------------
    case 'TOWN':
      $town = trim(stripslashes($input));

      try {
        $townId = Town::isTown($town);
      } catch (Exception $e) {
        if(ENV == 'dev') echo $e->getMessage();
        die();
      }
        
      return $townId;
      break;
      
    # check if input string is advertisement type --------------------
    case 'AD-TYPE':
      if (in_array($input, array('offer', 'demand'))) return true;
      else return false;
      break;
      
    # check if string is null ----------------
    case 'NOT-NULL':
      return (trim($input) != '');
      break;
      
    # check email ---------------------------
    case 'EMAIL':
      if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $input)) {
        return false;
      }
    
      $string_array = explode("@", $input);
      $local_array = explode(".", $string_array[0]);
      for ($i = 0; $i < sizeof($local_array); $i++) {
        if(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",$local_array[$i])) {
          return false;
        }
      }
    
      if (!ereg("^\[?[0-9\.]+\]?$", $string_array[1])) {
        $domain_array = explode(".", $string_array[1]);
        if (sizeof($domain_array) < 2) {
          return false;
        }
        for ($i = 0; $i < sizeof($domain_array); $i++) {
          if(!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$",$domain_array[$i])) {
            return false;
          }
        }
      }
    
      return true;
      break;
      
    # check telephone ------------------------
    case 'TELEPHONE':
      if (preg_match('/^\d{10,11}$/' ,$input) == true) return true;
      else return false;
      break;
      
    # default --------------------------------
    default:
      return true;
      break;
    
  }
}